package com.wenhao.utils;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 加法计数器
 * 共同屏障点
 *
 * @author Wenhao Tong
 * @create 2021-08-20 11:44
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,() -> {
            System.out.println("召唤神龙！");
        });
        // 如果只循环6次，那么将会永远等待
        for (int i = 1;i < 8;i++) {
            // lambda 只能接收声明为final的变量
            final int temp = i;
            new Thread(() -> {
                System.out.println("正在收集" + temp + "颗龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
